<template>
  <div class="h-full overflow-y-auto">
    <div class="card">
      <PageHeader class="p10 border-bottom">
        <div class="flex_aic">
          <div class="fs-14 font-600">{{ t('realtime.实时分析') }}</div>
          <el-tooltip
            :content="t('realtime.今日实时数据的统计时间均为今日零时至当前更新时间点击刷新按钮可强制更新')"
            placement="right"
            style="width: 300px"
          >
            <el-icon class="ml8" :size="16" color="#999999">
              <InfoFilled />
            </el-icon>
          </el-tooltip>
          <div class="ml8">{{ t('realtime.更新时间') }}{{ time }}</div>
          <el-icon
            @click="handleRefresh"
            class="ml8 cursor-pointer"
            :size="16"
            color="#999999"
          >
            <Refresh />
          </el-icon>
        </div>
      </PageHeader>

      <div class="p10 flex">
        <div class="titleBox flex_fdc_aic_jcc">
          <img src="@/assets/images/statistics/icon1.png" alt="" />
          <div class="mt6">{{ t('realtime.店铺汇总') }}</div>
        </div>
        <div class="flex flex1 gap-16 ml16">
          <div
            class="pl30 pt10 intoBox"
            v-for="item in baseList"
            :key="item.name"
          >
            <div class="fs-14 flex_aic">
              {{ item.name }}
              <el-tooltip
                :content="item.tips"
                placement="right"
                style="width: 300px"
                v-if="item.tips"
              >
                <el-icon class="ml8" :size="16" color="#999999">
                  <InfoFilled />
                </el-icon>
              </el-tooltip>
            </div>
            <div class="fs-28 mt10">{{ baseData?.[item.key] ?? "--" }}</div>
          </div>
        </div>
      </div>

      <div class="p10 flex">
        <div class="titleBox flex_fdc_aic_jcc">
          <img src="@/assets/images/statistics/icon2.png" alt="" />
          <div class="mt6">{{ t('realtime.今日实时') }}</div>
        </div>
        <div class="flex1">
          <div class="flex flex1 gap-16 ml16 mb16" v-for="list in todayData">
            <div
              class="pl30 pt10 intoBox"
              v-for="item in list"
              :key="item.name"
            >
              <div class="fs-14 flex_aic">
                {{ item.name }}
                <el-tooltip
                  :content="item.tips"
                  placement="right"
                  style="width: 300px"
                  v-if="item.tips"
                >
                  <el-icon class="ml8" :size="16" color="#999999">
                    <InfoFilled />
                  </el-icon>
                </el-tooltip>
              </div>
              <div class="fs-28 mt10">{{ baseData?.[item.key] ?? "--" }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="flex mt10 gap-10">
      <div class="card2">
        <PageHeader :title="t('realtime.分时会员新增趋势')" class="border-bottom p10" />
        <div id="chart1" class="chart_box"></div>
      </div>
      <div class="card2">
        <PageHeader :title="t('realtime.分时支付下单金额趋势')" class="border-bottom p10" />
        <div id="chart2" class="chart_box"></div>
      </div>
    </div>
    <div class="flex mt10 gap-10">
      <div class="card2">
        <PageHeader
          :title="`${t('realtime.实时商品销售排行')} - ${t('realtime.TOP10')}`"
          class="border-bottom p10"
        />
        <div class="p10">
          <el-table
            :data="tableData2"
            style="width: 100%"
            class="cover-table"
            border
            @sort-change="handleSortChange"
            :default-sort="tableSort"
            :loading="tableLoading"
            :key="tableKey"
          >
            <el-table-column type="index" :label="t('realtime.序号')" width="80" />
            <el-table-column :prop="'skuName' + locale" :label="t('realtime.商品名称')" />
            <el-table-column
              prop="saleAmount"
              :label="t('realtime.销售额')"
              sortable="custom"
            />
            <el-table-column
              prop="saleCount"
              :label="t('realtime.订单量')"
              sortable="custom"
            />
          </el-table>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted } from "vue";
import { InfoFilled, Refresh } from "@element-plus/icons-vue";
import * as echarts from "echarts";
import Api from "@/config/api/api";
import { useI18n } from "vue-i18n";
import moment from "moment";
const { t, locale } = useI18n();
const chart1 = null;
const chart2 = null;
const baseData = ref({});
const baseList = ref([
  {
    name: t('realtime.销售总额元'),
    key: "saleAmount",
  },
  {
    name: t('realtime.用户总数'),
    tips: t('realtime.在本店铺有过下单行为的历史去重人数总和'),
    key: "vipCount",
  },
  {
    name: t('realtime.订单量'),
    tips: t('realtime.在售商品数'),
    key: "saleCount",
  },
  // {
  //   name: "访客量",
  //   value: 0,
  //   tips: "截止至当前时间，关注店铺的累计用户数",
  // },
]);
const todayData = ref([
  [
    // {
    //   name: "今日销售额(元)",
    //   key: "todaySaleCreateAmount",
    //   tips: "今日0时至当前时间的销售额",
    // },
    {
      name: t('realtime.新增用户数'),
      key: "todayVipCount",
      tips: t('realtime.统计时间内首次在店铺下单的用户数'),
    },
    {
      name: t('realtime.新增商品数'),
      key: "todaySkuCount",
      tips: t('realtime.统计时间内店铺新增商品spu数'),
    },
    // {
    //   name: "动销商品数",
    //   key: "todaySkuCount",
    //   tips: "统计时间内，销量不为0的商品数",
    // },
  ],
  // [
  //   // {
  //   //   name: "店铺访客数",
  //   //   value: 0,
  //   //   tips: "统计时间内，店铺内所有页面被访问的去重人数",
  //   // },
  //   // {
  //   //   name: "店铺浏览量",
  //   //   value: 0,
  //   //   tips: "统计时间内，店铺内所有页面被访问的次数",
  //   // },
  //   {
  //     name: "商品访客数",
  //     value: 0,
  //     tips: "统计时间内，访问商品详情页的去重人数",
  //   },
  //   {
  //     name: "商品浏览量",
  //     value: 0,
  //     tips: "统计时间内，访问商品详情页的人次数",
  //   },
  // ],
  [
    {
      name: t('realtime.下单数'),
      key: "todaySaleCreateCount",
      tips: t('realtime.统计时间内该店铺成功提交订单的笔数总和'),
    },
    {
      name: t('realtime.下单人数'),
      key: "todaySaleCreateVipCount",
      tips: t('realtime.统计时间内成功提交订单的去重人数'),
    },
    {
      name: t('realtime.下单金额元'),
      key: "todaySaleCreateAmount",
      tips: t('realtime.统计时间内客户成功提交订单的总金额'),
    },
    {
      name: t('realtime.下单客单价元'),
      key: "todaySaleCreatePerAmount",
      tips: t('realtime.统计时间内下单金额下单人数'),
    },
    // {
    //   name: "访问-下单转化率",
    //   value: 0,
    //   tips: "统计时间内，下单人数/平台访客数",
    // },
  ],
  [
    {
      name: t('realtime.支付订单数'),
      key: "todaySaleCount",
      tips: t('realtime.统计时间内该店铺下所有已支付订单的总数量'),
    },
    {
      name: t('realtime.支付人数'),
      key: "todaySaleVipCount",
      tips: t('realtime.统计时间内成功付款的去重人数'),
    },
    {
      name: t('realtime.支付金额元'),
      key: "todaySaleAmount",
      tips: t('realtime.统计时间内所有支付订单金额之和'),
    },
    {
      name: t('realtime.支付客单价元'),
      key: "todaySalePerAmount",
      tips: t('realtime.统计时间内支付金额支付人数'),
    },
    // {
    //   name: "访问-支付转化率",
    //   value: 0,
    //   tips: "统计时间内，支付人数/平台访客数",
    // },
  ],
]);
const tableSort = ref({
  prop: "saleAmount",
  order: "descending",
});
const tableKey = ref(0);
const tableLoading = ref(false);
const tableData2 = ref([]);
const time = ref(moment().format("YYYY-MM-DD HH:mm:ss"));

const handleRefresh = () => {
  getBaseData();
  getChartData();
  tableSort.value = {
    prop: "saleAmount",
    order: "descending",
  };
  getTopData("saleAmountDesc");
  tableKey.value++;
  time.value = moment().format("YYYY-MM-DD HH:mm:ss");
};

const initChart = ({ id, chart, names, xData, datas }) => {
  const chartDom = document.getElementById(id);
  if (chart) chart.clear();
  chart = echarts.init(chartDom);
    const rgbs = [
      '33,195,188',
      '30,135,240',
    ]
  const option = {
    tooltip: {
      trigger: "axis",
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    legend: {
      data: names,
      selectedMode: true,
      icon: "circle",
      itemWidth: 12,
      itemHeight: 12,
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: xData,
    },
    yAxis: {
      type: "value",
      axisLine: {
        show: true,
        lineStyle: {
          color: "#999999",
        },
      },
    },
    series: datas.map((v, i)=> ({
      name: names[i],
        type: "line",
        smooth: true,
        data: v,
        itemStyle: {
          color: `rgba(${rgbs[i]},1)`,
        },
        areaStyle: {
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: `rgba(${rgbs[i]},0.9)`,
              },
              {
                offset: 1,
                color: `rgba(${rgbs[i]},0.9)`,
              },
            ],
          },
        },
    }))
  };

  option && chart.setOption(option);
};

const getBaseData = async () => {
  const res = await Api.realtime_summary();
  baseData.value = res.data || {};
};

const getChartData = () => {
  Api.vipAndTenantTrend({
    type: 1,
    startDate: moment().format("YYYY-MM-DD 00:00:00"),
    endDate: moment().format("YYYY-MM-DD 23:59:59"),
  }).then((res) => {
    initChart({
      id: "chart1",
      chart: chart1,
      names: [t('realtime.新增会员数')],
      xData: res.data?.map((item) => item.time) || [],
      datas: [res.data?.map((item) => item.vipCount) || []],
    });
  });

  Api.saleTrend().then((res) => {
    initChart({
      id: "chart2",
      chart: chart2,
      names: [t('realtime.下单金额'), t('realtime.支付金额')],
      xData: res.data?.map((item) => item.time) || [],
      datas: [res.data?.map((item) => item.saleCreateAmount) || [], res.data?.map((item) => item.saleAmount) || []],
    });
  });
};

const handleSortChange = ({ column, prop, order }) => {
  // 排序 saleAmountAsc销售额升序 saleAmountDesc销售额降序 saleCountAsc订单量升序 saleCountDesc订单量降序
  if (prop === "saleAmount") {
    getTopData(order === "ascending" ? "saleAmountAsc" : "saleAmountDesc");
  } else if (prop === "saleCount") {
    getTopData(order === "ascending" ? "saleCountAsc" : "saleCountDesc");
  }
};
const getTopData = (sort) => {
  tableLoading.value = true;
  Api.skuSaleTop10({
    sort,
    startDate: moment().format("YYYY-MM-DD 00:00:00"),
    endDate: moment().format("YYYY-MM-DD 23:59:59"),
  }).then((res) => {
    tableData2.value = res.data || [];
    tableLoading.value = false;
  });
};

onMounted(() => {
  getBaseData();
  getChartData();
  getTopData("saleAmountDesc");
});
</script>
<style lang="scss" scoped>
.card {
  background-color: #fff;
  border-radius: 2px;

  .border-bottom {
    border-bottom: 1px solid #e5e5e5;
  }

  .titleBox {
    width: 100px;
    background-color: #fff7f4;
  }

  .intoBox {
    border-radius: 2px;
    background-color: #eee3;
    height: 90px;
    width: calc((100% - 64px) / 5);
  }
}

.card2 {
  background-color: #fff;
  border-radius: 2px;
  width: calc((100% - 10px) / 2);
  .chart_box {
    height: 458px;
    margin-top: 30px;
  }
}
</style>
